angular.module('inventory.services', [])
/**
 * 实时库存清单
 */
.factory('InventoryService',function(){
  var getInventorySub = function(scope){
    return scope.subscribe('inventory');
  };
  return {
    overview : function(scope,conditions,callback){
      scope.helpers({
        inventory_alarm: function() {
          return Inventory.find(); 
        }
      });
      scope.autorun(function() {
        if(getInventorySub(scope).ready() && scope.inventory_alarm){
          var lowInventory=0,outOfInventory=0;
          var overview={stat:0,statInfo:'',alarmHref:''};
          if(!scope.inventory_alarm.length){
            overview.stat=1;
            overview.statInfo = '充足';
            overview.alarmHref= 'all';
          }else{
            scope.inventory_alarm.forEach(function(item){
              if(item.qty===0){
                outOfInventory++;
              }
              if(item.qty>0){
                lowInventory++;
              }
            });
            if(outOfInventory>0){
              overview.stat=3;
              overview.statInfo += outOfInventory+'款缺货';
            }
            if(lowInventory>0){
              overview.stat=outOfInventory===0?2:3;
              overview.statInfo+=overview.statInfo!==''?', ':'';
              overview.statInfo += lowInventory+'款库存低';
            }
            overview.alarmHref= 'alarm';
          }
          callback(overview);
        }
      });
    },
    //计算库存总价值
    caclValue: function(scope,conditions,callback){
      scope.helpers({
        inventory_all: function() {
          return Inventory.find(conditions,{fields:{qty:1,sale_price:1}});
        }
      });
      scope.autorun(function() {
        if(getInventorySub(scope).ready() && scope.inventory_all){
          var totalValue=0;
          scope.inventory_all.forEach(function(item){
            // console.log(item);
            totalValue+=item.sale_price*item.qty;
          });
          // console.log(scope.inventory_all);
          callback(totalValue);
        }
      });
    },

  /**
   * 列出库存商品
   */
    list: function(scope,conditions,callback){
      scope.helpers({
        inventory_list: function() {
          return Inventory.find(conditions,{fields:{distribution:0}});
        }
      });
      scope.autorun(function() {
        if(getInventorySub(scope).ready() && scope.inventory_list){
          var subtotal = {'totalCount':0,'totalValue':0,'totalValueMin':0};
          scope.inventory_list.forEach(function(item){
            // 总数量
            subtotal.totalCount+=item.qty;
            // 总价值
            subtotal.totalValue+=item.sale_price*item.qty;
            subtotal.totalValueMin+=item.min_sale_price*item.qty;
          });
          callback(scope.inventory_list,subtotal);
        }
     });
   },
   /**
    * 列出启用品牌，按照inventory库
    */
    getBrandList: function(scope,conditions,callback){
      scope.helpers({
        brandByInventory: function() {
          return Inventory.find(conditions,{fields:{qty:1,brand:1}});
        }
      });
      scope.autorun(function() {
        if(getInventorySub(scope).ready() && scope.brandByInventory){
          var brands={};
          scope.brandByInventory.forEach(function(item){
            if(!brands[item.brand.name]){
            	brands[item.brand.name]=item.brand;
            	brands[item.brand.name].count=item.qty;
            }else{
            	brands[item.brand.name].count+=item.qty;
            }
            if(!item.brand.logo || item.brand.logo===''){
              brands[item.brand.logo]='none';
            }
          });
          callback(brands);
         }
      });
    },
    //按照product_id 获取库存分布详情
    getDetailById:function(scope,conditions,callback){
      scope.helpers({
        inventoryDetail: function() {
          return Inventory.findOne(conditions);
        }
      });
    }
  };
})



// 弹窗 A confirm dialog
.directive('digestInventoryPopup', function($ionicPopup) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      scope.showConfirm = function() {
        var confirmPopup = $ionicPopup.confirm({
          title: '<b>消化库存</b>',
          template: '<p>销库存后该商品将不再出现在库存警报中。</p><p>建议仅将不再进货的商品设置为销库存。</p>',
          cancelText: '取消',
          okText: '确定',
          okType: 'button-royal',
        });
        confirmPopup.then(function(res) {
          if(res) {
            console.log('You are sure');
          } else {
            console.log('You are not sure');
          }
        });
      };
    }
  };
})

// 锁定库存
.directive('unLockInventory', function($ionicPopup) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      scope.toggleLock=function(item){
        item.islocked = !item.islocked;
      };
      scope.lockText=function(isLocked){
        return !isLocked?'锁定':'解除锁定';
      };
      scope.lockStatusText=function(isLocked){
        return isLocked?'未锁定':'已锁定';
      };
    }
  };
})

;
